"""
The MIT License (MIT)
Copyright © 2022 Walkline Wang (https://walkline.wang)
Gitee: https://gitee.com/walkline/espnow-remote-controller
"""
from machine import ADCBlock
from utils.dispatcher import Dispatcher
from config import Config


class JoyStick(object):
	def __init__(self, sampling_cb=None):
		self.__pin_list = Config.PINS.ADC.JOYSTICK_PINS
		self.__adc_list = []
		self.__last_sampling_list = []
		self.__sampling_cb = sampling_cb
		self.__adc_block = ADCBlock(1, bits=12)

		for _ in self.__pin_list:
			self.__adc_list.append(self.__adc_block.connect(_))
			self.__adc_list[-1].atten(2) # 2: ADC.ATTN_6DB: (0mV ~ 1300mV) ESP32C3
			self.__last_sampling_list.append(0)

		self.__adc_count = len(self.__adc_list)

	def deinit(self):
		for _ in self.__adc_list:
			_ = None

	def timer_callback(self, timer=None):
		# 每通道分别采样 1 次，采样 34 次
		sample_count = 34
		sample_avg = [0 for _ in range(self.__adc_count)]

		for _ in range(sample_count):
			for index in range(self.__adc_count):
				if _ < 2:
					self.__adc_list[index].read() # 丢弃两次采样结果
					continue

				# self.__adc_list[index].read_uv() # 直接读取校准后的电压值，单位：毫伏
				sample_avg[index] += self.__adc_list[index].read()

		for index in range(self.__adc_count):
			'''
			下式等效于 int(sample_avg / 16)
			- sample_avg >>= 1 = int(sample_avg / 2)
			- sample_avg >>= 2 = int(sample_avg / 4)
			- sample_avg >>= 3 = int(sample_avg / 8)
			'''
			sample_avg[index] >>= 5

			if abs(self.__last_sampling_list[index] - sample_avg[index]) > 7:
				self.__last_sampling_list[index] = sample_avg[index]

				if self.__sampling_cb:
					self.__sampling_cb(self.__pin_list[index], sample_avg[index])


		# 每通道连续采样 10 次
		# for index in range(len(self.__adc_list)):
		# 	sample_avg = 0

		#	self.__adc_list[index].read() # 丢弃两次采样结果
		#	self.__adc_list[index].read()

		# 	for _ in range(sample_count - 2): # 采样 10 次取平均值
		# 		sample_avg += self.__adc_list[index].read()

		# 	sample_avg >>= 3

		# 	if self.__last_sampling_list[index] != sample_avg and abs(self.__last_sampling_list[index] - sample_avg) > 9:
		# 		if self.__sampling_cb:
		# 			self.__sampling_cb(self.__pin_list[index], sample_avg)

		# 		self.__last_sampling_list[index] = sample_avg


def run_test():
	def sampling_cb(pin, value):
		print(f'pin: {pin}, value: {value}')

	joystick = JoyStick(sampling_cb)
	tasks = Dispatcher(2)

	joystick_task = lambda: joystick.timer_callback()
	tasks.add_work(joystick_task, 10)


if __name__ == '__main__':
	try:
		run_test()
	except KeyboardInterrupt:
		pass
